// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PicknPlaceAgentKukaRobotiq.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Manipulation.Runtime
{
    using System;
    using System.Runtime.Serialization;
    using Microsoft.Robotics.Hardware;
    using Microsoft.Robotics.Hardware.Robotiq;
    using Microsoft.Robotics.Hardware.Runtime.Robotiq;
    using Microsoft.Robotics.Manipulation.PicknPlace;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Tracing;

    /// <summary>
    /// Handles higher level "pick" and "place" commands for a Kuka arm plus Robotiq gripper. 
    /// </summary>
    [DataContract]
    public class PicknPlaceAgentKukaRobotiq : PicknPlaceAgentBase<RobotiqSModelControlMessage, RobotiqSModelStateMessage, CartesianGoalPositionControlMessage>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PicknPlaceAgentKukaRobotiq" /> class
        /// </summary>
        /// <param name="name">The name</param>
        /// <param name="producer">The name of the agent we subscribe to.</param>
        /// <param name="armControlAgentName">Name of the arm control agent</param>
        /// <param name="handControlAgentName">Name of the hand control agent</param>
        /// <param name="handStatusProvider">Name of agent providing integrated arm / hand status</param>
        /// <param name="armMoveRotationalTolerance">Tolerance on arm orientation moves in radians</param>
        /// <param name="armMoveTranslationalTolerance">Tolerance on arm move convergence in meters</param>
        /// <param name="liftHeight">Lift height from grasp position</param>
        /// <param name="defaultSubTaskStepTimeOutmSec">Time out in mSec at each step in pick and place tasks</param>
        /// <param name="gripExchangePose">Location used for grip exchange</param>
        /// <param name="defaultNeutralPose">Default neutral position before a pick or place</param>
        public PicknPlaceAgentKukaRobotiq(
            string name,
            IProducer<ManipulatorStatusMessage> producer,
            string armControlAgentName,
            string handControlAgentName,
            string handStatusProvider,
            double armMoveRotationalTolerance,
            double armMoveTranslationalTolerance,
            double liftHeight,
            int defaultSubTaskStepTimeOutmSec,
            Pose gripExchangePose,
            Pose defaultNeutralPose)
            : base(name, producer, armControlAgentName, handControlAgentName, handStatusProvider, armMoveRotationalTolerance, armMoveTranslationalTolerance, liftHeight, defaultSubTaskStepTimeOutmSec, gripExchangePose, defaultNeutralPose)
        {
        }

        /// <summary>
        /// Initializes the agent
        /// </summary>
        /// <param name="locator">Agent locator to use</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
            this.PicknPlaceGenerator = new PicknPlaceTaskDescriptionGenerator(new PicknPlaceKukaRobotiqGrip(), this.DefaultSubTaskStepTimeOutmSec);
        }

        /// <summary>
        /// Subscription receiver for hand messages
        /// </summary>
        /// <param name="message">The hand message</param>
        public override void Receive(RobotiqSModelStateMessage message)
        {
            if (this.Context != null)
            {
                byte fingerOpen;

                if (null == this.Context.TargetTask || this.Context.TargetTask.GripperState == null || this.Context.TargetTask.GripperState.GripStateEnum == GripperStatus.GripperStateEnum.Open)
                {
                    // Default case or when we want to open gripper find minimum open finger
                    fingerOpen = Math.Min(message.State.FingerAState.Position, message.State.FingerBState.Position);
                    fingerOpen = Math.Min(fingerOpen, message.State.FingerCState.Position);
                }
                else
                {
                    // Closed gripper - find most open finger
                    fingerOpen = Math.Max(message.State.FingerAState.Position, message.State.FingerBState.Position);
                    fingerOpen = Math.Max(fingerOpen, message.State.FingerCState.Position);
                }

                GripperStatus.FingerStateEnum fingerState = GripperStatus.FingerStateEnum.Stopped;

                if (message.State.FingerAState.FingerStatus == RobotiqSModelFingerStatus.InMotion ||
                    message.State.FingerBState.FingerStatus == RobotiqSModelFingerStatus.InMotion ||
                    message.State.FingerCState.FingerStatus == RobotiqSModelFingerStatus.InMotion)
                {
                    fingerState = GripperStatus.FingerStateEnum.InMotion;
                }

                double percentOpen = 100.0 - (Convert.ToDouble(fingerOpen) * 100.0 / 255.0);
                percentOpen = Math.Min(percentOpen, 100.0);
                percentOpen = Math.Max(percentOpen, 0);

                this.Context.CurrentHandState = new GripperStatus(
                    GripperStatus.GripperStateEnum.Unknown,
                    percentOpen,
                    fingerState,
                    GripStyle.Unknown);
            }
        }

        /// <summary>
        /// Publish a move an arm move message
        /// </summary>
        /// <param name="moveTo">Move to location</param>
        public override void PostArmMove(Pose moveTo)
        {
            Vector3 p = moveTo.Position;
            Quaternion q = moveTo.Orientation;
            TraceOut.Info(TraceContexts.Manip, "Arm Move [{0:F3} {1:F3} {2:F3}] [{3:F4} {4:F4} {5:F4} {6:F4}]", p.X, p.Y, p.Z, q.W, q.X, q.Y, q.Z);
            this.ArmControlAgentPort.Post(new CartesianGoalPositionControlMessage(
                                    AgentMessage.GetCurrentTime(),
                                    moveTo,
                                    this.ArmPositionMoveTolerance,
                                    this.ArmOrientationMoveTolerance));
        }

        /// <summary>
        /// Publish a move a hand move message
        /// </summary>
        /// <param name="gripperState">Target gripper state</param>
        public override void PostHandMove(GripperStatus gripperState)
        {
            RobotiqSModelGripModes grip;
            switch (gripperState.GripStyle)
            {
                case GripStyle.WrapAroundPrincipalAxisFace1:
                    grip = RobotiqSModelGripModes.Basic;
                    break;

                case GripStyle.TopDownAroundPrincipalAxis:
                    grip = RobotiqSModelGripModes.Pinch;
                    break;

                default:
                    grip = RobotiqSModelGripModes.Basic;
                    break;
            }

            double openAmount = (100.0 - gripperState.PercentOpen) * 255 / 100;
            openAmount = Math.Min(openAmount, byte.MaxValue);
            openAmount = Math.Max(openAmount, 0);

            RobotiqSModelBasicCommand basicCmd = new RobotiqSModelBasicCommand(
                true,
                grip,
                true,
                Convert.ToByte(openAmount),
                255,
                250);
            if (null != this.HandControlAgentPort)
            {
                this.HandControlAgentPort.Post(new RobotiqSModelControlMessage(AgentMessage.GetCurrentTime(), basicCmd, false));
            }
        }
    }
}
